package hhf.flex.ascreator;

import hhf.flex.ascreator.exceptions.ASFileExistException;
import hhf.flex.ascreator.patterns.ASDelayedFunctionPattern;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

public class ASDelayedServiceCreator {

    Set<String> _imports = new HashSet<String>();
    private String _path;
    private String _pack;
    private String _service;
    private String _className;
    private OutputStreamWriter _out;
    private String _argsTyped;
    private Method _method;

    public ASDelayedServiceCreator(Method method, Set<String> imports, String path, String pack, String className, String argsTyped) {
        this._imports = imports;
        this._method = method;
        this._service = className;
        this._className = className + "Delayed";
        this._pack = pack;
        this._path = path;
        this._argsTyped = argsTyped;
        try {
            this._out = createFile(pack, _className, path);
        } catch (ASFileExistException ex) {
            System.out.println("ASFileExistException " + ex);
        }
    }

    /**
     * Créé le fichier .as representant la classe
     * @param pack
     * @param className
     * @return
     */
    protected final OutputStreamWriter createFile(final String pack, final String className, String path) throws ASFileExistException {
        try {
            File rep = new File(path, pack.replaceAll("\\.", "/"));
            if (!rep.exists()) {
                rep.mkdirs();
            }
            File file = new File(rep, className + ".as");
            if (file.exists()) {
                throw new ASFileExistException();
            }
            return new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        } catch (UnsupportedEncodingException ex) {
            System.out.println("UnsupportedEncodingException " + ex);
        } catch (FileNotFoundException ex) {
            System.out.println("FileNotFoundException " + ex);
        }
        return null;
    }

    public void write() {

        try {
            ASDelayedFunctionPattern.writeFunction(_out, _pack, _className, _service, _argsTyped, _imports, _method);
            _out.flush();
            _out.close();
        } catch (IOException ex) {
            System.out.println("IOException " + ex);
        }
    }
}
